<?php

declare (strict_types = 1);

namespace app\service\admin\system;

use app\model\system\DeptModel;
use app\model\system\RoleModel;
use app\model\system\UserModel;
use own\auth\User;

class UserService
{
    protected $auth;

    public function __construct()
    {
        $this->auth = make(User::class);
    }
    /**
     * 列表
     * @param array $param
     */
    public function getList(array $param): array
    {
        $map = [];
        // 关键词搜索
        if($keyword = $param['keyword'] ?? '') {
            $map[] = ['username|phone', 'like', '%' . trim($keyword) . '%'];
        }
        // 用户名
        if($username = $param['username'] ?? '') {
            $map[] = ['username', 'like', '%' . trim($username) . '%'];
        }
        // 昵称
        if($nickname = $param['nickname'] ?? '') {
            $map[] = ['nickname', 'like', '%' . trim($nickname) . '%'];
        }
        // 电话
        if($phone = $param['phone'] ?? '') {
            $map[] = ['phone', 'like', '%' . trim($phone) . '%'];
        }
        // 状态
        $status = $param['status'] ?? '';
        if(is_numeric($status)) {
            $map[] = ['status', '=', $status];
        }
        $list = UserModel::where($map)
            ->with(['role', 'dept'])
            ->page($param['page'], $param['pageSize'])
            ->select();
        $total = UserModel::where($map)->count();
        return list_fmt($list, $total, $param);
    }
    /**
     * 编辑
     * @param array $data
     * @param integer $id
     */
    public function edit(array $data, int $id): void
    {
        // 部门
        if($data['dept_id'] && !DeptModel::find($data['dept_id'])) {
            tips('未找到选择的部门信息');
        }
        // 角色
        if($data['role_id'] && !RoleModel::find($data['role_id'])) {
            tips('未找到选择的角色信息');
        }
        if($id) {
            $user = UserModel::find($id);
            if(!$user){
                tips('无管理员【' .$data['username']. '】信息');
            }
            $user->updated_by = $this->auth->getUser();
        } else {
            $user = new UserModel();
            $user->username = trim($data['username']);
            // 账号查重
            $this->_usernameRepeat(1, $user->username);
            $user->password = md5(trim($data['encryption']?:'123456'));
            $user->created_by = $this->auth->getUser();
        }
        $user->phone = trim($data['phone']);
        // 手机号查重
        $this->_usernameRepeat(2, $user->phone, $id);

        $user->nickname = trim($data['nickname']);
        $user->email = trim($data['email']);
        $user->avatar = $data['avatar'];
        $user->signed = $data['signed'];
        $user->dashboard = $data['dashboard'];
        $user->dept_id = $data['dept_id'];
        $user->role_id = $data['role_id'];
        $user->status = $data['status'];
        $user->remark = $data['remark'];
        if(!$user->save()) {
            tips('保存失败');
        }
    }
    /**
     * 账号或电话号码查重
     * @param integer $type 类型: 1.账户 2.手机号
     * @param string $keyword
     * @param integer $id
     */
    protected function _usernameRepeat(int $type, string $keyword, $id = 0): void
    {
        $where = UserModel::whereIn('status', [1,2]);
        $type == 1 ? $where->where('username', $keyword) : $where->where('phone', $keyword);
        if($id) {
            $where->where('id', '<>', $id);
        }
        if($where->find()) {
            $str = $type == 1 ? '用户名' : '手机号';
            tips($str . '【' . $keyword. '】已被使用');
        }
    }
    /**
     * 用户密码重置
     * @param array $param
     */
    public function resetPassword(array $param): bool
    {
        $updata = ['password' => md5($param['encryption']), 'updated_by' => $this->auth->getUser()];
        return UserModel::whereIn('id', $param['ids'])->update($updata) ? true : false;
    }
    /**
     * 删除
     * @param integer $id 管理员id
     */
    public function delete(int $id): bool
    {
        return UserModel::where('id', $id)->delete() ? true : false;
    }
    /**
     * 修改状态
     * @param integer $id 管理员id
     */
    public function status(int $id): bool
    {
        $user = UserModel::find($id);
        if(!$user) {
            tips('无管理员信息');
        }
        $user->status = $user->status ? 0 : 1;
        $user->created_by = $this->auth->getUser();
        return $user->save() ? true : false;
    }
    /**
     * 修改秘密
     * @param array $param
     */
    public function modifyPassword(array $param): bool
    {
        $user = UserModel::find($this->auth->uid());
        if(!$user) {
            tips('修改密码失败');
        }
        if($user->password != md5($param['userPassword'])) {
            tips('密码不正确，修改失败');
        }
        $user->password = md5($param['confirmNewPassword']);
        return $user->save() ? true : false;
    }
    /**
     * 修改个人信息
     * @param array $param
     */
    public function modifyUser(array $param): bool
    {
        $user = UserModel::find($this->auth->uid());
        if(!$user) {
            tips('修改个人信息失败');
        }
        $user->nickname = trim($param['nickname']);
        $user->sex = $param['sex'];
        $user->email = $param['email'];
        $user->signed = $param['signed'];
        return $user->save() ? true : false;
    }
}